import React, { Component } from 'react'
import 'react-day-picker/lib/style.css'

const currentYear = new Date().getFullYear()
const fromMonth = new Date(currentYear - 2, 0)
const toMonth = new Date(currentYear + 10, 11)
const initMonth = new Date().getMonth()
const initDate = new Date(currentYear, initMonth)
const months = [
  '一月',
  '二月',
  '三月',
  '四月',
  '五月',
  '六月',
  '七月',
  '八月',
  '九月',
  '十月',
  '十一月',
  '十二月',
]

const years = []
for (let i = fromMonth.getFullYear(); i <= toMonth.getFullYear(); i += 1) {
  years.push(i)
}

export default class MonthAndYear extends Component {
  state = { month: initDate }

  handleChange = (e) => {
    let { year, month } = e.target.form
    if (month === undefined) {
      month = { value: 0 }
    }
    const { onChange } = this.props
    this.setState({ month: new Date(year.value, month.value) })
    onChange(month.value, year.value)
  }

  render() {
    const { month } = this.state
    const { yearOnly } = this.props
    return (
      <React.Fragment>
        <p style={{ display: 'inline', paddingRight: '1em' }}>{`请选择${yearOnly ? '年' : '月'}份:`}</p>
        <form className="DayPicker-Caption" style={{ display: 'contents' }}>
          {!yearOnly && (
            <select name="month" onChange={this.handleChange} value={month.getMonth()}>
              {months.map((month, i) => (
                <option key={month} value={i}>
                  {month}
                </option>
              ))}
            </select>
          )}
          <select name="year" onChange={this.handleChange} value={month.getFullYear()}>
            {years.map(year => (
              <option key={year} value={year}>
                {year}
              </option>
            ))}
          </select>
        </form>
      </React.Fragment>
    )
  }
}
